<template>
<div style="width: 100%">
  <a-page-header title="提交订单" @back="() => $router.go(-1)"/>
  <!--a-card title="填写收货信息" style="width: 100%">
    <a-row>
      <a-col :span="1">
        <h3>收货地址</h3>
      </a-col>
      <a-col :span="1"/>
      <a-col :span="3">
        <a-cascader :options="area_options" expand-trigger="hover" placeholder="请选择地域"/>
      </a-col>
      <a-col :span="9">
        <a-input placeholder="输入街道、门牌号、建筑名称及详细地址，例：孝陵卫200号南京理工大学明理居西门" ></a-input>
      </a-col>
    </a-row>
    <div style="height: 1vw"/>
    <a-row>
      <a-col :span="1">
        <h3>联系人</h3>
      </a-col>
      <a-col :span="1"/>
      <a-col :span="1">
        <h3>姓名：</h3>
      </a-col>
      <a-col :span="2">
        <a-input v-model="contactInfo.name" placeholder="请使用真实姓名"></a-input>
      </a-col>
      <a-col :span="2">
        <a-radio-group v-model="contactInfo.sex" :default-value="1">
          <a-radio-button :value="1">
            先生
          </a-radio-button>
          <a-radio-button :value="2">
            女士
          </a-radio-button>
        </a-radio-group>
      </a-col>
      <a-col :span="1"/>
      <a-col :span="2">
        <h3>联系方式：</h3>
      </a-col>
      <a-col :span="4">
        <a-input v-model="contactInfo.phone" placeholder="请输入手机号"></a-input>
      </a-col>
    </a-row>
    <div style="height: 1vw"/>
    <a-row>
      <a-col :span="2">
        <h3>预约送达时间</h3>
      </a-col>
      <a-col :span="1"/>
      <a-col :span="5">
        <a-select style="width: 100%" v-model:value="contactInfo.expectedDeliverTime">
          <a-select-option v-for="(item_D) in deliverTimes" :key="item_D">
            {{item_D}}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col :span="1"/>
      <a-col :span="3">
        <h3 style="color: #1890ff">{{contactInfo.expectedDeliverTime=='立即送出'?'大约'+getInstantOrderDTime:'将在'+contactInfo.expectedDeliverTime}}送达</h3>
      </a-col>
    </a-row>
  </a-card-->
  <a-card title="填写收货信息" style="width: 100%">
    <a-form-model :model="contactInfo" :label-col="labelCol" :wrapperCol="wrapperCol" :rules="rules" ref="ruleForm">
      <a-form-model-item label="地域" prop="region">
        <a-cascader v-model="contactInfo.region" :options="area_options" placeholder="请选择地域"/>
      </a-form-model-item>
      <a-form-model-item label="详细地址" prop="address">
        <a-input placeholder="输入街道、门牌号、建筑名称及详细地址，例：孝陵卫200号南京理工大学明理居西门" v-model="contactInfo.address"></a-input>
      </a-form-model-item>
      <a-form-model-item label="姓名" prop="name">
        <a-input v-model="contactInfo.name" placeholder="请使用真实姓名"></a-input>
      </a-form-model-item>
      <a-form-model-item label="称呼" prop="sex">
        <a-radio-group v-model="contactInfo.sex" :default-value="1">
          <a-radio-button :value="1">
            先生
          </a-radio-button>
          <a-radio-button :value="2">
            女士
          </a-radio-button>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="联系方式" prop="phone">
        <a-input v-model="contactInfo.phone" placeholder="请输入手机号"></a-input>
      </a-form-model-item>
      <a-form-model-item label="预约送达时间">
        <a-select style="width: 100%" v-model:value="contactInfo.expectedDeliverTime">
          <a-select-option v-for="(item_D) in deliverTimes" :key="item_D">
            {{item_D}}
          </a-select-option>
        </a-select>
        <h3 style="color: #1890ff">{{contactInfo.expectedDeliverTime=='立即送出'?'大约'+getInstantOrderDTime:'将在'+contactInfo.expectedDeliverTime}}送达</h3>
      </a-form-model-item>
    </a-form-model>
  </a-card>
  <div style="height: 1vw"/>
  <a-card :title="sellerData_submit.name" style="width: 100%">
    <a-list :data-source="cart_submit">
      <a-list-item slot="renderItem" slot-scope="item, index">
        <a-list-item-meta :description="'x'+item.thingNumber">
          <p slot="title">{{item.thingName}}</p>
          <a-avatar slot="avatar" :src="item.thingLogo"/>
        </a-list-item-meta>
        <h3 slot="actions">{{'￥'+(item.thingNumber*item.singlePrice).toFixed(2)}}</h3>
      </a-list-item>
      <a-list-item>
        <a-list-item-meta :description="'x'+getPackCost">
          <p slot="title">打包盒</p>
        </a-list-item-meta>
        <h3 slot="actions">{{'￥'+getPackCost*2}}</h3>
      </a-list-item>
    </a-list>
    <div style="height: 1vw"/>
    <a-row>
      <a-col :span="22"/>
      <a-col :span="1">
        <h3>小计</h3>
      </a-col>
      <a-col :span="1">
        <h2 style="font-weight: bold">{{'￥'+getBillSum}}</h2>
      </a-col>
    </a-row>
  </a-card>
  <div style="height: 1vw"/>
  <a-row style="background: #ffffff">
    <a-col :span="22"/>
    <a-col :span="2">
      <a-button type="primary" icon="money-collect" @click="submitOrder" size="large" :loading="loadingSubmitting">付款</a-button>
    </a-col>
  </a-row>
</div>
</template>

<script>
import options from "@/ref/options";
import {notification} from "ant-design-vue";
export default {
name: "Submit",
  data:function (){
    return{
      area_options:'',
      loadingSeller_submit:true,
      loadingSubmitting:false,
      sellerID:1,
      sellerData_submit:'',
      contactInfo:{
        name:'茄子',
        sex:1,
        phone:'18000000000',
        expectedDeliverTime:'立即送出',
        region:['江苏省','南京市','玄武区'],
        address:'孝陵卫200号南京理工大学'
      },
      times:[],
      deliverTimes:[],
      cart_submit:[],
      labelCol:{ span: 4 },
      wrapperCol: { span: 14 },
      rules:{
        region:[{required:true,message:'请选择您的地域信息',trigger:'change'}],
        address:[{required:true,message:'请填写您的详细地址',trigger:'blur'}],
        name: [
          { required: true, message: '请输入您的真实姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '姓名长度不合规', trigger: 'blur' }
        ],
        sex:[{required: true, message: '请选择您的称呼', trigger: 'blur' }],
        phone:[
          {required: true, message: '请输入您的中国大陆手机号码', trigger: 'blur' },
          {len: 11, message: '手机号码长度不合规', trigger: 'blur' }
        ]
      }
    }
  },
  methods:{
    getSellerInfo:function (){
      //请求商家信息
      let rearUrl=this.$store.state.rear_url
      this.$axios.post('http://'+rearUrl+'/sellerinfo',{
        sellerID:this.sellerID
      }).then((response)=>{
        this.loadingSeller_submit=false
        console.log(response.data)
        if(response.data.sellerInfoStatus!==0){
          notification.open({
            message:'请求商家信息失败',
            description:"请求商家信息时服务器返回了状态码1"
          })
        }else{
          this.sellerData_submit=response.data
          this.calcTimes()
          this.getDeliverTimes()
          console.log(this.deliverTimes)
        }
      }).catch((err)=>{
        this.loadingSeller_submit=false
        notification.open({
          message:'请求商家信息失败',
          description:"服务器错误："+err.message
        })
      })
    },
    calcTimes:function (){
      if(this.sellerData_submit==''){
        console.log("警告：在数据未接收时调用了送达时间计算")
        return
      }
      //times数组：0当前小时，1当前分钟，2-3商家关门时间，4-5商家开门时间
      let bHour=this.sellerData_submit.businessHour
      this.times[2]=parseInt(bHour.split("-")[1].split(":")[0])
      this.times[3]=parseInt(bHour.split("-")[1].split(":")[1])
      this.times[4]=parseInt(bHour.split("-")[0].split(":")[0])
      this.times[5]=parseInt(bHour.split("-")[0].split(":")[1])
    },
    calcDeliverTime:function (distance){
      if(distance<1000) return 30
      else{
        return((distance-1000)*(1/600)+30).toFixed(0)
      }
    },
    getDeliverTimes:function (){
      this.deliverTimes=['立即送出']
      let hh=this.times[0],mm=this.times[1],limitH=this.times[2],limitM=this.times[3]
      let costTime=parseInt(this.calcDeliverTime(this.sellerData_submit.range))

      //如果商家出售宵夜则将最晚送达时间.小时拓展
      if(this.times[2]<this.times[4]) {
        //如果当前时间已过零点则将当前时间加24
        if(0<hh&&hh<limitH) hh+=24
        limitH+=24
      }

      //如果当前商家还未开门，则取消立即送出选项并将起始时间设为商家营业时间
      if(hh*60+mm<this.times[4]*60+this.times[5]){
        this.deliverTimes=[]
        hh=this.times[4]
        mm=this.times[5]
        this.contactInfo.expectedDeliverTime=''
      }

      //计算最晚送达时间（=商家关门时间+骑手花费时间）
      limitM+=costTime

      //计算最早送达时间（=当前时间+骑手花费时间）
      mm+=costTime

      //消除超出59的分钟
      while (mm>59){
        hh++
        mm-=60
      }
      while (limitM>59){
        limitH++
        limitM-=60
      }
      console.log(hh+":"+mm+" "+limitH+":"+limitM)

      //抹平最早送达时间至单位为20min
      if(0<=mm&&mm<20){
        mm=20
      }else if(20<=mm&&mm<40) {
        mm=40
      }else{
        mm=0
        hh++
      }

      //循环计算给出10个可用送达时间
      for(let i=0;(hh*60+mm < limitH*60+limitM)&&i<10;i++){
        this.deliverTimes.push(this.fixedTwice(hh>23?hh-24:hh)+':'+this.fixedTwice(mm))
        mm+=20
        if(mm>59){
          hh++
          mm-=60
        }
      }

      //设置默认选项为第一个选项
        this.contactInfo.expectedDeliverTime=this.deliverTimes[0]
    },
    //将number固定显示为两位并转为string
    fixedTwice:function (n) {
      if(n<10) return '0'+n.toString()
      else return n.toString()
    },
    submitOrder:function (){
      this.$refs.ruleForm.validate(valid=>{
      if(valid){
        this.loadingSubmitting=true
        let rearUrl=this.$store.state.rear_url
        this.$axios.post('http://'+rearUrl+'/submit',{
          userID:this.$store.state.userID,
          token:this.$store.state.token,
          sellerID:this.sellerID,
          orderState:1,
          cart:this.cart_submit,
          contactInfo:this.contactInfo
        }).then((res)=>{
          this.loadingSubmitting=false
          console.log(res.data)
          if(res.data.submitStatus!==0){
            notification.open({
              message:'用户验证失败',
              description:"请重新登录饿死了么账号"
            })
            window.location='/#/login'
          }else{
            this.$store.commit('clearCart')
            window.location='/#/confirmed?orderID='+res.data.orderID
          }
        }).catch((err)=>{
          this.loadingSubmitting=false
          notification.open({
            message:'订单提交失败',
            description:"服务器错误："+err.message
          })
        })
      }else{
        notification.open({
          message:'收货信息不完整或不符合规范',
          description:"请将收货信息填写至无误后提交订单"
        })
      }
    })
    }
  },
  created() {
    console.log("ruleForm:")
    if(this.$store.state.userName=='') {
      notification.open({
        message:'非法的页面请求',
        description:"未登录用户尝试访问订单提交页面"
      })
      window.location='/#/'
      return
    }
    if(this.$store.state.cart.length==0||this.$store.state.sellerID=='') {
      notification.open({
        message:'非法的页面请求',
        description:"用户尝试跳过菜单访问订单提交页面"
      })
      window.location='/#/'
      return
    }
    if(this.$store.state.sellerID!=this.$route.query.sellerID) {
      notification.open({
        message:'非法的页面请求',
        description:"请求的商家ID与购物车的商家ID不符"
      })
      window.location='/#/'
      return
    }
    if(!this.$store.getters.userInfoComplete) {
      notification.open({
        message:'用户信息不完整',
        description:"请重新登录饿死了么账号"
      })
      window.location='/#/login'
      return
    }

    this.area_options=options.options

    let date=new Date()
    this.times[0]=date.getHours()
    this.times[1]=date.getMinutes()

    this.sellerID=this.$route.query.sellerID
    this.cart_submit=this.$store.state.cart
    console.log(this.cart_submit)
    this.getSellerInfo()
  },
  computed:{
    getInstantOrderDTime:function (){
      let hh=this.times[0],mm=this.times[1]
      mm+=parseInt(this.calcDeliverTime(this.sellerData_submit.range))
      while(mm>59) {
        mm-=60
        hh++
      }
      if(hh>23) hh-=24
      console.log(hh+mm)
      return this.fixedTwice(hh)+':'+this.fixedTwice(mm)
    },
    getPackCost:function (){
      let thingNum=0
      this.cart_submit.forEach((item)=>{
        thingNum+=item.thingNumber
      })
      return thingNum
    },
    getBillSum:function (){
      let sum=0
      this.cart_submit.forEach((item)=>{
        sum+=item.thingNumber*item.singlePrice
      })
      return (sum+this.getPackCost*2).toFixed(2)
    }
  }
}
</script>

<style scoped>

</style>